package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 实现俩个线程，先打印2再打印1
 * 方法1：synchronized关键字、wait()、notify() {@link Thread12}
 * 方法2：ReentrantLock、await、signal {@link Thread13}
 * 方法3：park与unpark (通行证策略){@link Thread14}
 * 方法1与方法2相似
 *
 * @author Hush.
 * @since 2023/5/18 12:53
 */
@Slf4j
public class Thread13 {
    static final ReentrantLock lock = new ReentrantLock();
    static Condition c = lock.newCondition();

    static boolean FLAG = false;


    public static void main(String[] args) {
        new Thread(() -> {
            try {
                lock.lock();
                while (!FLAG) {
                    try {
                        c.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.info("1");
            } finally {
                lock.unlock();
            }
        }, "t-1").start();

        new Thread(() -> {
            try {
                lock.lock();
                FLAG = true;
                c.signal();
                log.info("2");
            } finally {
                lock.unlock();
            }

        }, "t2").start();

    }
}
